package smstpl

import (
	"context"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/dao"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/model"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/model/entity"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

// ProcessTemplateIdByAliasAndFrom 通过变量别名和平台类型获取模板ID
func (t *sSmsTpl) ProcessTemplateIdByAliasAndFrom(ctx context.Context, varAlias, fromType string) (*string, error) {
	item := &model.SmsOutItem{}
	// 读取数据
	err := t.OutModel().Scan(ctx, g.Map{
		dao.SmsTemplateOut.Columns().VarAlias: varAlias,
		dao.SmsTemplateOut.Columns().FromType: fromType,
	}, &item)
	if err != nil {
		return nil, err
	}
	// 是否查询数据
	if item == nil {
		return nil, gerror.New(`未查询到模板数据`)
	}
	return &item.TemplateId, nil
}

// ProcessTemplateOutMapByAlias 通过模板变量获取外部模板数据MAP
func (t *sSmsTpl) ProcessTemplateOutMapByAlias(ctx context.Context, fromType string, varAlias ...string) (map[string]*entity.SmsTemplateOut, error) {
	if len(varAlias) == 0 {
		return nil, gerror.New(`模板变量不能为空`)
	}
	var (
		list   []entity.SmsTemplateOut
		outMap = make(map[string]*entity.SmsTemplateOut)
	)

	// 获取数据
	err := t.OutModel().Scan(ctx, g.Map{
		dao.SmsTemplateOut.Columns().VarAlias: varAlias,
		dao.SmsTemplateOut.Columns().FromType: fromType,
	}, &list)
	if err != nil {
		return nil, err
	}

	// 数据不存在
	if len(list) == 0 {
		return nil, gerror.New(`暂无数据`)
	}

	// 迭代处理数据
	for _, item := range list {
		outMap[item.VarAlias] = &item
	}
	return outMap, nil
}
